﻿//* Write a program that reads a positive integer number N (N < 20) from console and outputs in the console the numbers 1 ... N numbers arranged as a spiral.

using System;

class PrintNumbersInSpiral
{
    static void Main()
    {
        Console.Write("Enter N = ");
        string numberString = Console.ReadLine();
        int number;
        if (int.TryParse(numberString, out number) && number > 1 && number < 20)
        {
            int row = 0;
            int col = 0;
            string direction = "right";
            int[,] matrix = new int[number, number];
            for (int i = 1; i <= number * number; i++)
            {
                matrix[row, col] = i;
                if (direction == "right")
                {
                    col++;
                    if (col == number - 1 || matrix[row, col + 1] != 0)
                    {
                        direction = "down";
                    }
                }
                else if (direction == "down")
                {
                    row++;
                    if (row == number - 1 || matrix[row + 1, col] != 0)
                    {
                        direction = "left";
                    }
                }
                else if (direction == "left")
                {
                    col--;
                    if (col == 0 || matrix[row, col - 1] != 0)
                    {
                        direction = "up";
                    }
                }
                else if (direction == "up")
                {
                    row--;
                    if (row == 0 || matrix[row - 1, col] != 0)
                    {
                        direction = "right";
                    }
                }
            }

            //print matrix
            for (int r = 0; r < number; r++)
            {
                for (int c = 0; c < number; c++)
                {
                    Console.Write("{0,4}", matrix[r, c]);
                }
                Console.WriteLine();
            }
        }
        else
        {
            Console.WriteLine("Out of range (1 < N < 20) !");
        }
    }
}
